package com.ruicar.afs.cloud.manage.insurance.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.manage.common.entity.ManageApprovalRecord;
import com.ruicar.afs.cloud.manage.common.service.ManageApprovalRecordService;
import com.ruicar.afs.cloud.manage.insurance.condition.ManageInsuranceInfoCondition;
import com.ruicar.afs.cloud.manage.insurance.entity.ManageInsuranceInfo;
import com.ruicar.afs.cloud.manage.insurance.service.ManageInsuranceInfoService;
import com.ruicar.afs.cloud.manage.insurance.service.PrintTemplateService;
import com.ruicar.afs.cloud.manage.workflow.entity.WorkTaskAssignInfo;
import com.ruicar.afs.cloud.manage.workflow.processor.ApproveTaskProcessor;
import com.ruicar.afs.cloud.manage.workflow.service.WorkTaskAssignInfoService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author xudongdong
 * @date 2020-06-08
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/insurance")
public class ManageInsuranceController {

    private final PrintTemplateService printTemplateService;
    private final ApproveTaskProcessor approveTaskProcessor;
    private final ManageInsuranceInfoService insuranceInfoService;
    private final WorkTaskAssignInfoService workTaskAssignInfoService;
    private final ManageApprovalRecordService manageApprovalRecordService;

    @PostMapping("/getInsuranceInfoList")
    @ApiOperation(value = "获取保险业务数据 多条件")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<IPage<ManageInsuranceInfo>> getInsuranceInfoList(@RequestBody QueryCondition<ManageInsuranceInfoCondition> insuranceClaimCondition) {
        Page page = new Page(insuranceClaimCondition.getPageNumber(), insuranceClaimCondition.getPageSize());
        insuranceClaimCondition.getCondition().setProcessPerson(SecurityUtils.getUser().getUsername());
        insuranceClaimCondition.getCondition().setRoleCodeList(SecurityUtils.getUser().getRoleCodeList());
        insuranceClaimCondition.getCondition().getRoleCodeList().add(SecurityUtils.getUser().getUsername());
        IPage<ManageInsuranceInfo> list;
        if (insuranceClaimCondition.getCondition().getCaseAll()) {
            list = insuranceInfoService.getInsuranceInfoList(page, insuranceClaimCondition.getCondition());
            for (ManageInsuranceInfo insuranceInfo : list.getRecords()) {
                ManageApprovalRecord manageApprovalRecord = manageApprovalRecordService.getOne(Wrappers.<ManageApprovalRecord>query().lambda()
                        .eq(ManageApprovalRecord::getContractNo, insuranceInfo.getContractNo())
                        .eq(ManageApprovalRecord::getCaseNo, insuranceInfo.getCaseNo())
                        .orderByDesc(ManageApprovalRecord::getCreateTime), false);
                WorkTaskAssignInfo workTaskAssignInfo = workTaskAssignInfoService.getOne(Wrappers.<WorkTaskAssignInfo>lambdaQuery().
                        eq(WorkTaskAssignInfo::getBizDataId, insuranceInfo.getId()).orderByDesc(WorkTaskAssignInfo::getId), false);
                insuranceInfo.setDispatchTime(workTaskAssignInfo != null ? workTaskAssignInfo.getCreateTime() : null);
                if (EmptyUtils.isEmpty(manageApprovalRecord)) {
                    insuranceInfo.setProcessPerson(insuranceInfo.getApplyBy());
                } else {
                    insuranceInfo.setProcessPerson(manageApprovalRecord.getProcessPerson());
                }
            }
        } else {
            list = insuranceInfoService.insuranceInfoList(page, insuranceClaimCondition.getCondition());
            for (ManageInsuranceInfo insuranceInfo : list.getRecords()) {
                ManageApprovalRecord manageApprovalRecord = manageApprovalRecordService.getOne(Wrappers.<ManageApprovalRecord>query().lambda()
                        .eq(ManageApprovalRecord::getContractNo, insuranceInfo.getContractNo())
                        .eq(ManageApprovalRecord::getCaseNo, insuranceInfo.getCaseNo())
                        .orderByDesc(ManageApprovalRecord::getCreateTime), false);
                WorkTaskAssignInfo workTaskAssignInfo = workTaskAssignInfoService.getOne(Wrappers.<WorkTaskAssignInfo>lambdaQuery().
                        eq(WorkTaskAssignInfo::getBizDataId, insuranceInfo.getId()).orderByDesc(WorkTaskAssignInfo::getId), false);
                insuranceInfo.setDispatchTime(workTaskAssignInfo != null ? workTaskAssignInfo.getCreateTime() : null);
                if (EmptyUtils.isEmpty(manageApprovalRecord)) {
                    insuranceInfo.setProcessPerson(insuranceInfo.getApplyBy());
                } else {
                    insuranceInfo.setProcessPerson(manageApprovalRecord.getProcessPerson());
                }
            }
        }
        page.setRecords(approveTaskProcessor.handle(page.getRecords()));
        return IResponse.success(list);
    }

    @PostMapping("/saveInsurance")
    @ApiOperation(value = "保存保险业务信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<ManageInsuranceInfo> saveInsurance(@RequestBody ManageInsuranceInfoCondition insuranceClaimCondition) {
        ManageInsuranceInfo manageInsuranceInfo = insuranceInfoService.saveInsurance(insuranceClaimCondition);
        return new IResponse<ManageInsuranceInfo>().setData(manageInsuranceInfo);
    }

    @PostMapping("/submitInsurance")
    @ApiOperation(value = "提交保险业务信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse submitInsurance(@RequestBody ManageInsuranceInfoCondition insuranceClaimCondition) {
        insuranceInfoService.submitInsurance(insuranceClaimCondition);
        return new IResponse<Boolean>().setData(true).setMsg("流程提交成功！");
    }

    @PostMapping("/saveProposalApplicationInfo")
    @ApiOperation(value = "保存保险业务审批信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse saveProposalApplicationInfo(@RequestBody ManageInsuranceInfoCondition insuranceClaimCondition) {
        insuranceInfoService.saveProposalApplicationInfo(insuranceClaimCondition);
        return new IResponse<Boolean>().setData(true).setMsg("流程提交成功！");
    }

    @ApiOperation(value = "根据合同号码查询保险信息")
    @PostMapping("/getInsuranceData")
    public IResponse getInsuranceData(@RequestParam("caseNo") String caseNo) {
        ManageInsuranceInfo insuranceInfo = insuranceInfoService.getOne(Wrappers.<ManageInsuranceInfo>lambdaQuery()
                .eq(ManageInsuranceInfo::getCaseNo, caseNo));
        return new IResponse().setData(insuranceInfo);
    }

    @ApiOperation(value = "获取处理意见数据")
    @PostMapping("/getApprovalOpinion")
    public IResponse getApprovalOpinion(@RequestParam("contractNo") String contractNo, @RequestParam("caseNo") String caseNo) {
        ManageApprovalRecord manageApprovalRecord = manageApprovalRecordService.getOne(Wrappers.<ManageApprovalRecord>query().lambda()
                .eq(ManageApprovalRecord::getContractNo, contractNo)
                .eq(ManageApprovalRecord::getCaseNo, caseNo)
                .orderByDesc(ManageApprovalRecord::getCreateTime), false);
        return new IResponse().setData(manageApprovalRecord);
    }

    @Transactional
    @SysLog("删除保险业务信息")
    @ApiOperation(value = "通过id删除")
    @RequestMapping(value = "/delById/{id}", method = RequestMethod.DELETE)
    public IResponse<Boolean> delById(@PathVariable String id) {
        //删除保险业务详细信息表
        insuranceInfoService.removeById(id);
        return new IResponse<Boolean>().setMsg("删除成功");
    }

    @PostMapping("/PrintTemplate")
    @ApiOperation(value = "打印无章授权文件模板")
    public IResponse PrintTemplate(HttpServletResponse response, @RequestBody ManageInsuranceInfo manageInsuranceInfo) {
        printTemplateService.PrintTemplate(response, manageInsuranceInfo, "no");
        return new IResponse<Boolean>().setData(true).setMsg("打印授权文件模板成功！");
    }

    @PostMapping("/PrintHaveTemplate")
    @ApiOperation(value = "打印有章授权文件模板")
    public IResponse PrintHaveTemplate(HttpServletResponse response, @RequestBody ManageInsuranceInfo manageInsuranceInfo) {
        printTemplateService.PrintTemplate(response, manageInsuranceInfo, "yes");
        return new IResponse<Boolean>().setData(true).setMsg("打印授权文件模板成功！");
    }

    @PostMapping("/insuranceProgress")
    @ApiOperation(value = "根据身份证号码或者合同号码查询保险理赔进度（CMS接口聚合使用）")
    public IResponse<List<ManageInsuranceInfo>> insuranceProgress(@RequestParam(name = "idCard", required = false) String idCard, @RequestParam(name = "contractNo", required = false) String contractNo) {
        if ((EmptyUtils.isEmpty(idCard) || "null".equals(idCard)) && (EmptyUtils.isEmpty(contractNo) || "null".equals(contractNo))) {
            return new IResponse().fail("合同号码和证件号码不能同时为空");
        }
        List<ManageInsuranceInfo> list = insuranceInfoService.list(Wrappers.<ManageInsuranceInfo>query().lambda()
                .eq((EmptyUtils.isEmpty(idCard) || "null".equals(idCard)) && EmptyUtils.isNotEmpty(contractNo), ManageInsuranceInfo::getContractNo, contractNo)
                .eq(EmptyUtils.isNotEmpty(idCard) && !"null".equals(idCard), ManageInsuranceInfo::getCertNo, idCard));
        if (EmptyUtils.isEmpty(list)) {
            return new IResponse().fail("没有查询到保险理赔数据");
        }
        if (EmptyUtils.isEmpty(list)) {
            return new IResponse().fail("没有查询到");
        }
        return new IResponse<List<ManageInsuranceInfo>>().setData(list);
    }

}
